/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius4.resolver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class HandleRedirector extends Redirector {

    private static final Logger logger = Logger.getLogger(HandleRedirector.class.getName());
    private static final String PROP_MAPPING_FILE = "resolver.mappingFile";
    private static final String HANDLE_PREFIX = "/kramerius/handle/";
    private static final String K4_URI = "search";
    private IdMapper idMapper = null;

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        lazyLoadIdMapper();

        K3Identifier k3Id = parseK3Id(request.getRequestURI());
        if (k3Id == null) {
            logger.log(Level.WARNING, "Illegal url {0}", request.getRequestURI());
            redirectToK4(request, response, "ERROR");
            return;
        }
        String uuid = idMapper.findUuid(k3Id);
        if (uuid == null) {
            logger.log(Level.WARNING, "No uuid found for {0}", k3Id);
            redirectToK4(request, response, "ERROR");
            return;
        }
        redirectToK4(request, response, uuid);
        return;
    }

    private void lazyLoadIdMapper() throws IOException {
        if (idMapper == null) {
            try {
                String propertiesFile = "resolver.properties";
                InputStream inputStream = HandleRedirector.class.getClassLoader().getResourceAsStream(propertiesFile);
                PropertyLoader loader = new PropertyLoader(inputStream);
                File mappingFile = loader.loadFile(PROP_MAPPING_FILE, true);
                idMapper = new IdMapper(mappingFile);
            } catch (DocumentException ex) {
                throw new IOException(ex);
            }
        }
    }

    private K3Identifier parseK3Id(String requestURI) {
        if (!requestURI.startsWith(HANDLE_PREFIX)) {
            logger.log(Level.WARNING, "incorrect request uri ''{0}''", requestURI);
            return null;
        }
        String siglaNumber = requestURI.substring(HANDLE_PREFIX.length());
        String[] split = siglaNumber.split("/");
        if (split.length != 2) {
            logger.log(Level.WARNING, "incorrect request uri ''{0}''", requestURI);
            return null;
        }
        return new K3Identifier(split[0], split[1]);
    }
//    private void redirectToK4(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        ServletContext sc = null;
//        sc = getServletContext().getContext("/search");
//        RequestDispatcher rd = sc.getRequestDispatcher("/handle/uuid:ERROR");
//        rd.forward(request, response);
//    }
}
